package cn.xiongxf.pet.service.impl;

import cn.xiongxf.basic.service.impl.BaseServiceImpl;
import cn.xiongxf.pet.domain.PetType;
import cn.xiongxf.pet.mapper.PetTypeMapper;
import cn.xiongxf.pet.service.IPetTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {
    @Autowired
    private PetTypeMapper petTypeMapper;

    @Override
    public List<PetType> petTypeTree() {
        // 将所有（宠物类型id,宠物类型）存入map中
        Map<Long, PetType> map = new HashMap<>();
        List<PetType> petTypes = petTypeMapper.loadAll();
        for (PetType petType : petTypes) {
            map.put(petType.getId(),petType);
        }

        // 创建宠物类型树集合
        List<PetType> petTypeTree = new ArrayList<>();
        for (PetType petType : petTypes) {
            Long pid = petType.getPid();
            if (pid == null){
                // 顶级宠物类型，直接添加到宠物类型树
                petTypeTree.add(petType);
            }else {
                //PetType parentPetType = petTypeMapper.loadById(pid); 【这种方法要查 （行数-顶级个数）次 单个对象，用map只需一次查询所有】
                // 非顶级宠物类型，放入上级宠物类型的子宠物类型集合中
                PetType parentPetType = map.get(pid);
                parentPetType.getChildren().add(petType);
            }
        }
        return petTypeTree;
    }
}
